﻿using Serilog.Events;
using Serilog;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Serilog.Sinks.RichTextBox.Themes;
using TMI85303.UI.View;
using System.Diagnostics.Eventing.Reader;
using TMI85303.Utils;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using TMI85303.UI.Messages;
using System.Configuration;
using System.Reflection;
using System.Data.Entity.Infrastructure;
using TMI85303.UI.ViewModels;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Globalization;
using System.Windows.Threading;

namespace TMI85303
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml 12V 0.3A
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        private DispatcherTimer VersionHistoryTimer;

        public MainWindow()
        {
            InitializeComponent();

            Init();

            InitVersionDisplay();
        }

        private void Init()
        {
            richTextBoxLog.Loaded += (s, e) =>
            {
                var scrollViewer = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(richTextBoxLog, 0), 0) as ScrollViewer;
                scrollViewer.ScrollChanged += (scroller, eScroller) => ScrollViewer_ScrollChanged(scroller, eScroller);
            };
            InitLog();

            //GlobalApp.uiSQLiteConn = new SQLiteHelper(PathHelper.DbPath);
            //if (!GlobalApp.uiSQLiteConn.Open()) throw new Exception($"不能打开数据库：{GlobalApp.uiSQLiteConn.DataFile}");


        }

        private void InitLog()
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                //.WriteTo.Debug()  //Vs的Debug调试窗口
                .WriteTo.Async(a => a.File(  //单个日志文件，总日志，所有日志存到这里面
                    $"logs\\log.txt",
                    rollingInterval: RollingInterval.Day,
                    restrictedToMinimumLevel: LogEventLevel.Information,
                    rollOnFileSizeLimit: true,
                    fileSizeLimitBytes: 10485760, //10M
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"))
                //.WriteTo.File(  //单个日志文件，总日志，所有日志存到这里面
                //    $"logs\\log.txt",
                //    rollingInterval: RollingInterval.Day,
                //    restrictedToMinimumLevel: LogEventLevel.Information,
                //    rollOnFileSizeLimit: true,
                //    fileSizeLimitBytes: 10485760, //10M
                //    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
                .WriteTo.RichTextBox(richTextBoxLog, 2000,
                    outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
                    theme: RichTextBoxConsoleTheme.GrayscaleWhite)
                .CreateLogger();


            Log.Information("Starting application.");

        }

        private bool AutoScroll = true;

        private void ScrollViewer_ScrollChanged(object scroller, ScrollChangedEventArgs e)
        {
            // User scroll event : set or unset autoscroll mode
            if (e.Source as ScrollViewer != null && e.ExtentHeightChange == 0)
            {   // Content unchanged : user scroll event
                if ((e.Source as ScrollViewer).VerticalOffset == (e.Source as ScrollViewer).ScrollableHeight)
                {   // Scroll bar is in bottom
                    // Set autoscroll mode
                    AutoScroll = true;
                }
                else
                {   // Scroll bar isn't in bottom
                    // Unset autoscroll mode
                    AutoScroll = false;
                }
            }

            // Content scroll event : autoscroll eventually
            if (AutoScroll && e.ExtentHeightChange != 0 && e.Source as ScrollViewer != null)
            {
                (e.Source as ScrollViewer)?.ScrollToVerticalOffset((e.Source as ScrollViewer).ExtentHeight);
            }
        }

        private void MenuItemClick(object sender, RoutedEventArgs e)
        {
            MenuItem? clickedMenuItem = sender as MenuItem;
            string? menuItemId = clickedMenuItem?.Tag as string;
            switch (menuItemId)
            {
                case "OpenSystemSettingWin": new SystemConfigWin().ShowDialog(); break;
                case "OpenBookTMI85303CN":
                    try
                    {
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                        {
                            FileName = AppDomain.CurrentDomain.BaseDirectory + "books\\TMI85303_DS_CN_V1.2.pdf",
                            UseShellExecute = true
                        });
                    }
                    catch(Exception)
                    {
                        MessageBox.Show("抱歉！缺少手册文件");
                    }break;
                case "OpenBookTMI85303EN":
                    try
                    {
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                        {
                            FileName = AppDomain.CurrentDomain.BaseDirectory + "books\\TMI85303_DS_EN_V1.2.pdf",
                            UseShellExecute = true
                        });
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("抱歉！缺少手册文件");
                    }
                    break;
                default: break;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            WeakReferenceMessenger.Default.Send<WriteFileMTPDataConfig,int>(new(), (int)MesgToken.MTP_DATA);
            //GlobalApp.uiSQLiteConn?.Close();
        }

        private void Hyperlink_Company(object sender, RequestNavigateEventArgs e)
        {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
            {
                FileName = e.Uri.AbsoluteUri,
                UseShellExecute = true // 在.NET Core及更高版本中需要设置UseShellExecute为true
            });
            e.Handled = true; // 表示已处理该导航请求
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
            {
                FileName = "https://www.toll-semi.com/",
                UseShellExecute = true
            });
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            WeakReferenceMessenger.Default.Send<ReadFileMTPDataConfig,int>(new(), (int)MesgToken.MTP_DATA);

        }

        private void richTextBoxLog_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            richTextBoxLog.Document.Blocks.Clear();
        }

        private void ChangeChinese(object sender, RoutedEventArgs e) => LanguageManager.Instance.ChangeLang(new(Lang.Chinese));

        private void ChangeEnglish(object sender, RoutedEventArgs e) => LanguageManager.Instance.ChangeLang(new(Lang.English));

        // 当鼠标在其他页面点击时，把校验和进行忽略
        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source is TabControl tabControl)
            {
                var selectedTabItem = tabControl.SelectedItem as TabItem;
                var userControl = selectedTabItem?.Content as UserControl;
                if(userControl != null && userControl != MTPControl && MTPControl?.DataContext is EEPROMData model) 
                {
                    model.MTPCheckSumResult = EEPROMData.CheckSumInvalid;
                    model.ShadowCheckSumResult = EEPROMData.CheckSumInvalid;
                }
            }
        }

        private void AboutWin(object sender, RoutedEventArgs e) => new AboutWin().ShowDialog();

        private void HistoryWin(object sender, RoutedEventArgs e) => new VersionHistory().ShowDialog();

        private void InitVersionDisplay()
        {
            VersionHistoryTimer = new()
            {
                Interval = TimeSpan.FromMilliseconds(800)
            };
            VersionHistoryTimer.Tick += (s, e) =>
            {
                if (CommFun.IsFirstRun())
                {
                    CommFun.UpdateAppConfigFirstRunSetting();
                    var win = new VersionHistory();
                    win.ShowDialog();
                }
                VersionHistoryTimer.Stop();
            };
            VersionHistoryTimer.Start(); // 启动定时器
        }

    }
}